<!-- 保养计划列表 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <div class="content">
    <div class="content-header">
      <div>
        <a-space>
          <div>
            <a-input-search
              :style="{ width: 'auto' }"
              placeholder="请输入"
              v-model="currEquipNumber"
              search-button
              @search="search"
            >
              <template #prefix>设备编码：</template>
              <template #button-icon>
                <icon-search />
              </template>
            </a-input-search>
          </div>
          <div>
            <!-- <span> 设备名称： </span> -->
            <a-input
              :style="{ width: 'auto' }"
              placeholder="请输入设备名称"
              v-model="currEquipName"
              search-button
              @change="search"
            >
              <template #prefix>设备名称：</template>
              <!-- <template #button-icon>
            <icon-search />
          </template> -->
            </a-input>
          </div>

          <a-button type="primary" @change="search">
            <template #icon>
              <icon-search />
            </template>
            <template #default>搜索</template>
          </a-button>
        </a-space>
      </div>
      <div>
        <a-space>
          <a-button type="outline" @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            <template #default>重置</template>
          </a-button>

          <a-button status="success">
            <template #icon>
              <icon-download />
            </template>
            <template #default>导入</template>
          </a-button>
          <a-button status="warning">
            <template #icon>
              <icon-export :rotate="-90" />
            </template>
            <template #default>导出</template>
          </a-button>
        </a-space>
      </div>
    </div>
    <a-divider />
    <div>
      <TableTurn :args="args" :table-data="getData" ref="tableRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          :width="150"
          align="center"
          title="设备编码"
          data-index="equipNumber"
        >
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="设备名称"
          data-index="equipName"
        >
        </a-table-column>
        <a-table-column
          :width="150"
          align="center"
          title="保养计划名称"
          data-index="planName"
        >
        </a-table-column>
        <!-- <a-table-column
          :width="150"
          align="center"
          title="所属车间"
          data-index="workshop"
        >
          <template #cell="{ record }">
            {{
              workshop.filter((ele) => ele.id === record.workshopId)[0]?.value
            }}
          </template>
        </a-table-column> -->
        <a-table-column :width="150" align="center" title="保养周期">
          <template #cell="{ record }">
            {{
              `${record.maintenanceCycleNum}/${sumFn(
                record.maintenanceCycleUnit
              )}`
            }}
          </template>
        </a-table-column>
        <a-table-column :width="150" align="center" title="保养到期预警">
          <template #cell="{ record }">
            {{
              `${record.maintenanceWarning}/${sumFn(
                record.maintenanceCycleUnit
              )}`
            }}
          </template>
        </a-table-column>
        <a-table-column align="center" :width="100" fixed="right" title="操作">
          <template #cell="{ record }">
            <!-- <a-button type="text" @click="goDetail(record, 6)"
              >新建保养</a-button
            > -->
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goDetail(record, 11)"
              />
            </a-tooltip>
            <a-tooltip content="计划详情">
              <IconFont
                type="icon-details-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goDetail(record, 12)"
              />
            </a-tooltip>
          </template>
        </a-table-column>
      </TableTurn>
      <equipmentRepair
        :type="type"
        :form="form.list"
        v-model:visible="unkeepVisible"
        @equipmentEmit="equipmentEmit"
      ></equipmentRepair>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import { reactive, ref, onMounted } from 'vue';
  import { PutEquipmentPlan } from '@/api/equipment-management/equipment-list';
  import {
    GetEquipmentPlanList,
    PostMaintenanceEquipment,
  } from '@/api/equipment-management/equipment-maintain-manager';
  import equipmentRepair from '../../components/equipment-repair/index.vue';

  const router = useRouter();
  const title: string = '保养计划列表';
  const breadCrumb: string[] = ['设备管理', '设备维护（管理）', '保养计划列表'];
  // 车间假数据
  const workshop = [
    { id: 1, value: '车间A' },
    { id: 2, value: '车间B' },
    { id: 3, value: '车间C' },
    { id: 4, value: '车间D' },
  ];
  // 表格配置
  const args = reactive({
    stripe: true,
    bordered: {
      headerCell: true,
    },
  });

  let tableRef = ref(); // 储存table的ref

  const form = reactive({
    list: {},
  });

  let type = ref(1); // 判断弹出框的type

  let currEquipNumber = ref(''); // 设备编码搜索框

  let currEquipName = ref(''); // 设备名称搜索框

  // 获取表格数据
  const getData = async (pageData?: any) => {
    try {
      const data: any = {};
      if (currEquipNumber.value.trim() !== '')
        data.equipNumber = currEquipNumber.value;
      if (currEquipName.value.trim() !== '')
        data.equipName = currEquipName.value;
      const res: any = await GetEquipmentPlanList({
        ...pageData,
        ...data,
      });

      // 将保养周期的数据转成json格式
      // for (let i of res.content) {
      //   i.cycle = JSON.parse(i.cycle);
      // }
      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 搜索框事件
  const search = () => {
    tableRef.value.loadData();
  };

  let unkeepVisible = ref(false); // 判断是否显示弹出框

  // 前往编辑或者详情页面 type: 10编辑 11详情
  const goDetail = (record: any, currType: number) => {
    type.value = currType;
    form.list = record;
    unkeepVisible.value = true;
  };

  // 弹出框的自定义事件
  const equipmentEmit = async (list: any, type: number) => {
    try {
      // 编辑保养计划
      if (type === 11) {
        await PutEquipmentPlan({ ...list });
        tableRef.value.loadData();
      }
      // 新建设备保养单
      else if (type === 6) {
        const data = {
          planId: list.id,
          number: list.number,
          equipNumber: list.equipNumber,
          equipName: list.equipNumber,
          workshop: list.workshop,
          cycle: JSON.stringify({
            equipmentCycleUnit: list.cycle.equipmentCycleUnit,
            equipmentCycleVal: list.cycle.equipmentCycleVal,
          }),
          maintenanceWarning: list.maintenanceWarning,
          planContent: list.planContent,
          planStandard: list.planStandard,
          maintainState: 1, // 保养状态，新增默认传1
        };
        await PostMaintenanceEquipment(data);
      }
      unkeepVisible.value = false;
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };
  const emuipmentAge = [
    {
      value: 1,
      label: '时间',
      children: [
        { value: 3, label: '天' },
        { value: 2, label: '月' },
        { value: 1, label: '年' },
      ],
    },
    {
      value: 4,
      label: '数量',
      children: [
        { value: 4, label: '件' },
        { value: 5, label: '个' },
        { value: 6, label: '条' },
        { value: 7, label: '台' },
      ],
    },
  ];
  const sumFn = (sum: number) => {
    if (sum > 3) {
      return emuipmentAge[1].children.filter((ele) => ele.value === sum)[0]
        ?.label;
    } else {
      return emuipmentAge[0].children.filter((ele) => ele.value === sum)[0]
        ?.label;
    }
  };
  // 重置
  const reset = () => {
    currEquipNumber.value = '';
    currEquipName.value = '';
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .content {
    padding: 5px 10px;
    // padding: 0 40px;
    &-header {
      display: flex;
      width: 100%;
      height: 40px;
      margin-bottom: -5px;
      justify-content: space-between;
    }
  }
</style>
